const hre = require('hardhat');

// Usage examples:
// npx hardhat run scripts/check-code.js --network mainnet --address 0x1234...
// ADDRESS=0x1234... npx hardhat run scripts/check-code.js --network mainnet
// (默认地址为 0x881fb2f98c13d521009464e7d1cbf16e1b394e8e)

async function main() {
  const address = process.env.ADDRESS || getArgValue('--address') || '0x881fb2f98c13d521009464e7d1cbf16e1b394e8e';
  if (!/^0x[a-fA-F0-9]{40}$/.test(address)) {
    throw new Error('无效地址: ' + address);
  }
  console.log('Network:', hre.network.name);
  console.log('Checking address:', address);
  const code = await hre.ethers.provider.getCode(address);
  const isContract = code && code !== '0x';
  console.log('Code size (bytes):', (code.length - 2) / 2);
  console.log('Is contract?:', isContract);
  if (!isContract) {
    console.log('该地址上没有合约字节码 (EOA 或 未部署).');
  } else {
    // 打印前 40 bytes 预览
    console.log('Bytecode preview:', code.slice(0, 2 + 40));
  }
}

function getArgValue(flag) {
  const idx = process.argv.indexOf(flag);
  if (idx !== -1 && idx + 1 < process.argv.length) {
    return process.argv[idx + 1];
  }
  return null;
}

main().catch(e => { console.error(e); process.exit(1); });
